﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;

namespace DFYE.Web.Areas.manage.Controllers
{
    using JULONG.WEB.Library;
    using Models;
    public class uploadController : Controller
    {
        //
        // GET: /manage/uload/

        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 公司介绍 上传的图片
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string siteLibrary() {
            if (Request.Files.Count == 0) { return xhEditorJson.error("失败"); }
            HttpPostedFileBase hpfb = Request.Files[0];
            return xhEditorJson.success(NormalUpload(hpfb, "/content/uploads/siteLibrary/"));

        }
        [HttpPost]
        public string documentPic()
        {
            if (Request.Files.Count == 0) { return xhEditorJson.error("失败"); }
            HttpPostedFileBase hpfb = Request.Files[0];
            return xhEditorJson.success(NormalUpload(hpfb, "/content/uploads/document/"));
        }

        [HttpPost]
        public string file(string id)
        {
            if (Request.Files.Count == 0) { return xhEditorJson.error("失败"); }
            HttpPostedFileBase file = Request.Files[0];
            return xhEditorJson.success(NormalUpload(file, "/content/uploads/" + id + "/"));
        }
        

        [NonAction]
        public string NormalUpload(HttpPostedFileBase file, String pathFolder)
        {

            string _newFile = DateTime.Now.ToFileTime().ToString() + "." + file.FileName.Substring(file.FileName.LastIndexOf(".") + 1);
            string filePath = Server.MapPath(pathFolder + _newFile);
            GetPath(pathFolder);
            file.SaveAs(filePath);
            return pathFolder + _newFile;
                 
        }

        /// <summary>
        /// 创建目录并返回完全路径
        /// </summary>
        /// <param name="path"></param>
        private string GetPath(string path)
        {
            path = AppDomain.CurrentDomain.BaseDirectory + path;
            if (Directory.Exists(path)) return path;
            
            try
            {
                Directory.CreateDirectory(path);
            }
            catch
            {
                throw new Exception("不能创建目录!");
            }
            return path;
        }        

    }
}
